package com.hhlkeepalive.onePx;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import java.lang.ref.WeakReference;

public class ScreenListenerManager {
    private final Receiver mReceiver;
    private WeakReference<Context> mReference;
    private OnScreenListener mScreenListener;

    public ScreenListenerManager(Context context) {
        mReference = new WeakReference<>(context);
        mReceiver = new Receiver();
    }

    public void register() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        mReference.get().registerReceiver(mReceiver, filter);
    }

    public void unRegister() {
        mReference.get().unregisterReceiver(mReceiver);
    }

    public class Receiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (mScreenListener == null) return;
            switch (action) {
                case Intent.ACTION_SCREEN_ON: // 开屏
                    mScreenListener.onScreenOn();
                    break;
                case Intent.ACTION_SCREEN_OFF: // 锁屏
                    mScreenListener.onScreenOff();
                    break;
                case Intent.ACTION_USER_PRESENT: // 解锁
                    mScreenListener.onUserresent();
                    break;
            }
        }
    }

    public void setOnScreenListener(OnScreenListener listener) {
        mScreenListener = listener;
    }

    public interface OnScreenListener{
        void onScreenOn();
        void onScreenOff();
        void onUserresent();
    }
}
